<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!--      提示-->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!--步骤条  active="0 激活项索引-->
      <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!--tab栏-->
      <el-form :model="AddForm" :rules="AddFormRules" ref="AddFormRef" label-width="100px" label-position="top">
        <el-tabs :tab-position="'left'" v-model="activeIndex"
                 :before-leave="tabBefere"
                 @tab-click="tabClick">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="AddForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="AddForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="AddForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="AddForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader expand-trigger="hover" :options="cateList" :props="cateProps"
                           @change="handChange" v-model="AddForm.goods_cat">

              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox v-for="(item1,i) in item.attr_vals" border :key="i" :label="item1"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_vals[0]"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!--
            action上传的服务器地址
            handlePreview 图片预览函数
            handleRemove 处理移出图片函数
            list-type 指定图片呈现效果
            on-success 上传成功回调函数
            -->
            <el-upload
              :action="uploadUrl"
              :on-preview="handlePreview"
              :headers="uploadHeader"
              :on-remove="handleRemove"
              :on-success="uploadSuccess"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
<!--            富文本编辑器-->
            <quill-editor v-model="AddForm.goods_introduce">
            </quill-editor>
            <el-button type="primary" class="addBtn" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!--    图片预览对话框-->
    <el-dialog
      title="图片预览"
      :visible.sync="predialogVisible"
      width="50%">
      <img :src="preView" alt="" class="preImage">
    </el-dialog>
  </div>
</template>
<script>
import _ from 'lodash'
export default {
  data() {
    return {
      //对话框隐藏
      predialogVisible: false,
      //预览的真实地址
      preView: '',
      //上传图片的Header
      uploadHeader: {
        Authorization: window.sessionStorage.getItem('token')
      },
      //上传图片的地址
      uploadUrl: 'http://localhost:8888/api/private/v1/upload',
      //动态参数数据列表
      manyTableData: [],
      onlyTableData: [],
      //当前激活的步骤
      activeIndex: '0',
      //添加商品的表单对象
      AddForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        //被选中的分类id
        goods_cat: [],
        //图片
        pics: [],
        //商品介绍
        goods_introduce:'',
        attrs:[]
      },
      //校验规则
      AddFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      //商品分类列表
      cateList: [],
      cateProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      }
    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    //当前选中的cateId
    cateId() {
      if (this.AddForm.goods_cat.length === 3) {
        return this.AddForm.goods_cat[2]
      }
      return null
    }
  },
  methods: {
    //添加商品
     addGoods(){
      this.$refs.AddFormRef.validate(async valid => {
        if(!valid) {
          return this.$message.error('请检查表单是否完整！')
        }
        // 检验通过 添加商品
        //拷贝一份AddFrom因为原来的数组 需要和级联选择器数据绑定 不能改成字符串
        const form = _.clone(this.AddForm)
        //数组formt改成字符串
        form.goods_cat = form.goods_cat.join(',')
        //处理attrs
        this.manyTableData.forEach((item)=>{
          const newInfo = {
            attr_id : item.attr_id,
            attr_value : item.attr_vals.join(' ')
          }
          form.attrs.push(newInfo)
        })
        this.onlyTableData.forEach((item)=>{
          const newInfo = {
            attr_id : item.attr_id,
            attr_value : item.attr_vals
          }
          form.attrs.push(newInfo)
        })
        // console.log(form)
        //发起请求
        const { data: res } = await this.$http.post(`goods`, form)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success('添加商品成功！')
        this.$router.push('/goods')
      })
    },
    //上传图片成功回调
    uploadSuccess(res) {
      //将图片保存到数组中
      const picInfo = { pic: res.data.tmp_path }
      this.AddForm.pics.push(picInfo)
    },
    //处理移出图片函数
    handleRemove(file) {
      // file是将要删除的文件
      //图片的临时路径
      const filePath = file.response.data.tmp_path
      // console.log(filePath)
      //从pics中获得索引
      const i = this.AddForm.pics.findIndex((x) => {
        x.pic === filePath
      })
      // console.log("i"+i)
      //移除
      this.AddForm.pics.splice(i, 1)
      // console.log(this.AddForm.pics)
    },
    //图片预览函数
    handlePreview(file) {
      this.preView = file.response.data.url
      this.predialogVisible = true
    },
    //tab点击事件
    async tabClick() {
      //选择了动态参数tab
      if (this.activeIndex === '1') {
        //发起请求
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'many' }
        })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTableData = res.data
      }
      //选择了静态属性tab
      else if (this.activeIndex === '2') {
//发起请求
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'only' }
        })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.onlyTableData = res.data
        console.log(this.onlyTableData)
      }
    },
    //tab改变事件
    tabBefere() {
      if (this.AddForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类！')
        return false
      }
    },
    //选择器改变事件
    handChange() {
      if (this.AddForm.goods_cat.length !== 3) {
        this.AddForm.goods_cat = []
        return
      }
    },
    //获取所有分类数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.cateList = res.data
      // console.log(this.cateList)
    }
  }
}
</script>
<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.preImage{
  width: 100%;
}
.addBtn{
  margin-top: 15px;
}

</style>